package com.smile.mybatis;

import java.io.*;
import java.nio.file.*;
import java.util.regex.*;
import java.util.*;

public class SequenceGenerator {

    /**
     * 解析SQL文件并为每个表生成自增序列代码
     * @param inputFilePath 输入文件路径
     * @param outputFilePath 输出文件路径
     * @param schemaName 模式名称，用于替换"cfdp_bit"
     * @throws IOException 文件读写异常
     * @param isGS 是否是高斯数据库   高斯所有的对象都是小写（大小写敏感）
     *
     *
     * ALTER TABLE "cfdp_bit"."AU_Authorization" ADD CONSTRAINT "PK_dbo.AU_Authorization" PRIMARY KEY ("ID");
     *
     * CREATE SEQUENCE "public"."au_authorization_id_seq";
     * ALTER TABLE "public"."AU_Authorization" ALTER COLUMN "ID" SET DEFAULT nextval('"public"."au_authorization_id_seq"');
     * ALTER SEQUENCE "public"."au_authorization_id_seq" OWNED BY "public"."AU_Authorization"."ID";
     * SELECT setval('"public"."au_authorization_id_seq"', (SELECT MAX("ID") FROM "public"."AU_Authorization"));
     *
     *
     *
     */
    public static void generateSequences(String inputFilePath, String outputFilePath, String schemaName, boolean isGS) throws IOException {
        Path path = Paths.get(inputFilePath);
        if (!Files.exists(path)) {
            System.err.println("文件不存在: " + inputFilePath);
            return;
        }
        StringBuilder id = new StringBuilder("ID");
        if (isGS) {
            id = new StringBuilder("id");
        }


        // 读取输入文件的所有行

        List<String> readAllLines = Files.readAllLines(path);

        // 存储生成的序列代码
        List<String> sequenceStatements = new ArrayList<>();

        // 正则表达式匹配表名
        Pattern tablePattern = Pattern.compile("\"([^\"]+)\"\\.\"([^\"]+)\"");

        // 用于存储已处理的表，避免重复处理
        Set<String> processedTables = new HashSet<>();

        for (String line : readAllLines) {
            Matcher matcher = tablePattern.matcher(line);
            if (line.matches(".*PRIMARY KEY \\(\"[Ii][Dd]\"\\).*")) {
                if (matcher.find()) {
                    // 提取模式名和表名
                    //ALTER TABLE "cfdp_bit"."AU_Authorization" ADD CONSTRAINT "PK_dbo.AU_Authorization" PRIMARY KEY ("ID");
                    String originalSchema = matcher.group(1);
                    String tableName = matcher.group(2);
                    // 如果表已经处理过，则跳过
                    if (processedTables.contains(tableName)) {
                        continue;
                    }
                    // 添加到已处理表集合
                    processedTables.add(tableName);

                    // 生成序列名（转为小写并添加后缀）
                    String sequenceName = tableName.toLowerCase() + "_id_seq";

                    // 生成序列创建语句
                    sequenceStatements.add("-- 为" + tableName + "表创建自增ID");
                    sequenceStatements.add("CREATE SEQUENCE \"" + schemaName + "\".\"" + sequenceName + "\";");

                    // 生成设置默认值语句
                    sequenceStatements.add("ALTER TABLE \"" + schemaName + "\".\"" + tableName + "\" ALTER COLUMN \"" + id + "\" SET DEFAULT nextval('\"" + schemaName + "\".\"" + sequenceName + "\"');");

                    // 生成序列归属语句
                    sequenceStatements.add("ALTER SEQUENCE \"" + schemaName + "\".\"" + sequenceName + "\" OWNED BY \"" + schemaName + "\".\"" + tableName + "\".\"" + id + "\";");

                    // 生成设置序列值语句
                    sequenceStatements.add("SELECT setval('\"" + schemaName + "\".\"" + sequenceName + "\"', (SELECT MAX(\"" + id + "\") FROM \"" + schemaName + "\".\"" + tableName + "\"));");
                    sequenceStatements.add(""); // 添加空行分隔





                }
            }


        }
        // 将生成的语句写入输出文件
        Files.write(Paths.get(outputFilePath), sequenceStatements,
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);

        System.out.println("处理完成，共生成 " + processedTables.size() + " 个表的序列代码");

    }

    public static void main(String[] args) {
        try {
            // 使用示例：输入文件路径、输出文件路径、目标模式名
            generateSequences("C:\\Users\\14002\\Desktop\\k高斯ID.txt", "C:\\Users\\14002\\Desktop\\k高斯ID自增.txt", "public", true);
        } catch (IOException e) {
            System.err.println("文件处理错误: " + e.getMessage());
            e.printStackTrace();
        }
    }


}
